package swingUI;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;

import mySwingToolkit.controller.TableController;
import mySwingToolkit.model.ClassModel;
import mySwingToolkit.model.SwitchedTableModel;
import mySwingToolkit.ui.ButtonTabComponent;
import mySwingToolkit.ui.TableView;

import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.api.skin.SubstanceGeminiLookAndFeel;

import com.trsjh.db.controller.Home;
import com.trsjh.db.domains.Customer;
import com.trsjh.db.domains.CustomerAccount;
import com.trsjh.db.domains.Good;
import com.trsjh.db.utils.ExcelUtil;

public class App {

	private static final String CUSTOMER="CUSTOMER";
	private static final String USER="USER";
	private static final String ADD_CUSTOMER = "ADD_CUSTOMER";
	private static final String TAB_CUSTOMER1="用户查询1";
	public static final String TAB_CUSTOMER2="用户查询2";
	private static final String TAB_GOOD_VIEW="商品查看";
	private static final String TAB_GOODTYPE="商品类型";
	public static final String TAB_CUSTOMERRECORDS = "购买记录";
	public static final String TAB_ADD_CUSTOMER = "添加新用户";
	
	public static final String MENU_CUSTOMER_ALL = "顾客全览";
	public static final String MENU_CUSTOMER_EXPORT = "导出顾客";
	public static final String MENU_CUSTOMER_SEND = "发送消息";

	
	private JFrame frame;
	private JTabbedPane tabbedPane;
	public static  List<Good> goods;
	
	TableView tv;
	private static void changeSkin(App  window){
		//三种界面风格
		//String windows="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
		//String metal="javax.swing.plaf.metal.MetalLookAndFeel";
		//String motif="com.sun.java.swing.plaf.motif.MotifLookAndFeel";
		try{
			//						  UIManager.setLookAndFeel(metal);
			//						  font font=new font("jframe",font.plain,14);
			//						  enumeration keys=uimanager.getlookandfeeldefaults().keys();
			//						  while(keys.hasmoreelements()){
			//						  object key=keys.nextelement();
			//						  if(uimanager.get(key)instanceof font) uimanager.put(key.font);
			//						  }
			//SubstanceLookAndFeel.setSkin(new BusinessBlackSteelSkin());
			SubstanceLookAndFeel slf= new  SubstanceGeminiLookAndFeel();
			window.frame.getRootPane().putClientProperty(SubstanceLookAndFeel.WATERMARK_VISIBLE, true);
			UIManager.setLookAndFeel(slf); 

			SwingUtilities.updateComponentTreeUI(window.frame);
		} 
		catch   (Exception   e){ 
			System.out.println( "无法设置界面风格 "); 
		} 
	}
	//	static class MySkin extends org.pushingpixels.substance.api.skin.BusinessBlackSteelSkin{
	//		public MySkin(){
	//	        super();
	//	        SubstanceImageWatermark imageWatermark = new SubstanceImageWatermark(App.class.getResourceAsStream("/images/back.jpg"));
	//	        imageWatermark.setOpacity(0.7f);
	//	        imageWatermark.setKind(ImageWatermarkKind.APP_CENTER);
	//	        this.watermark = imageWatermark;
	//	    }
	//	}
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					JFrame.setDefaultLookAndFeelDecorated(true);
					App window = new App();
					changeSkin(window);
					window.frame.setVisible(true);

				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public App() {
		initialize();
		this.initDatas();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(App.class.getResource("/images/background.jpg")));
		frame.setTitle("天然水晶行客户管理软件 "+new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
		frame.setBounds(100, 100, 640, 480);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));

		JToolBar toolBar = new JToolBar();
		frame.getContentPane().add(toolBar, BorderLayout.NORTH);

		JButton button = this.makeNavigationButton("find.png", CUSTOMER, "查询客户", "查询");
		toolBar.add(button);
		JButton button2 = this.makeNavigationButton("addCustomer.png", ADD_CUSTOMER, "添加新客户", "新客户");
		toolBar.add(button2);

		//		JButton button3 = this.makeNavigationButton("user.gif", USER, "查询员工信息", "员工信息");
		//		toolBar.add(button3);


		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setToolTipText("");
		frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
		tabbedPane.addChangeListener(new ChangeListener(){
			@Override
			public void stateChanged(ChangeEvent e) {
				if(tabbedPane.getSelectedComponent() instanceof MyUI)
					((MyUI)tabbedPane.getSelectedComponent()).refresh();
			}

		});

		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);

		JMenu mnNewMenu = new JMenu("操作");
		menuBar.add(mnNewMenu);

		JMenuItem menuItem = new JMenuItem("商品类型");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				GoodTypeUI goodTypeUI=new GoodTypeUI();
				tabbedPane.addTab( TAB_GOODTYPE,null, goodTypeUI);
				tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(goodTypeUI), new ButtonTabComponent(tabbedPane));
			}
		});
		mnNewMenu.add(menuItem);

		JMenuItem menuItem_1 = new JMenuItem("商品编辑");
		menuItem_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GoodUI goodUI=new GoodUI();
				tabbedPane.addTab("商品编辑",null, goodUI);
				tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(goodUI), new ButtonTabComponent(tabbedPane));
			}
		});
		mnNewMenu.add(menuItem_1);

		JMenuItem menuItem_2 = new JMenuItem("查看商品");
		menuItem_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Good good=null;
				List<Good> list=new ArrayList<Good>();
				good=new Good();
				good.setName("1");
				list.add(good);
				good=new Good();
				good.setName("2");
				list.add(good);
				good=new Good();
				good.setName("3");
				list.add(good);
				good=new Good();
				good.setName("4");
				list.add(good);
				good=new Good();
				good.setName("5");
				list.add(good);
				good=new Good();
				good.setName("6");
				list.add(good);
				good=new Good();
				good.setName("7");
				list.add(good);
				good=new Good();
				good.setName("8");
				list.add(good);
				good=new Good();
				good.setName("9");
				list.add(good);
				good=new Good();
				good.setName("10");
				list.add(good);
				good=new Good();
				good.setName("11");
				list.add(good);
				good=new Good();
				good.setName("12");
				list.add(good);
				good=new Good();
				good.setName("13");
				list.add(good);
				@SuppressWarnings({ "serial", "unchecked" })
				TableView<Good> tableView=new GoodView<Good>(
						new SwitchedTableModel<Good>(
								new Object[][] {
								},
								new String[] {
										"名字", "类型", "品牌", "价格", "底价", "描述", "图片"
								},
								new Class[] {
										String.class, String.class, String.class, String.class, String.class, String.class, String.class
								},
								new boolean[] {
										true, true, true, true, true, true, true
								},false,false,false
								){
							@SuppressWarnings("unchecked")
							@Override
							public Object[] translate(ClassModel<Good> goodClass) {
								Good good=goodClass.getObject();
								@SuppressWarnings("rawtypes")
								List datas=new ArrayList();
								datas.add(goodClass);
								datas.add(this.getRowCount()+1);
								if(good.getName()!=null)
									datas.add(good.getName());
								else
									datas.add("");
								if(good.getBrand()!=null)
									datas.add(good.getBrand());
								else
									datas.add("");
								if(good.getPrice()!=null)
									datas.add(good.getPrice());
								else
									datas.add("");
								if(good.getLowerPrice()!=null)
									datas.add(good.getLowerPrice());
								else
									datas.add("");
								if(good.getDescription()!=null)
									datas.add(good.getDescription());
								else
									datas.add("");
								if(good.getPhotos()!=null)
									datas.add(good.getPhotos());
								else
									datas.add("");
								return datas.toArray();
							}
							@Override
							public Good constructObject(int row,int col) {
								ClassModel<Good> cm=(ClassModel<Good>) this.getValueAt(row, 0);
								Good good=null;
								if(cm!=null){
									good=cm.getObject();
								}else{
									good=new Good();
								}
								switch(col){
								case TableModelEvent.ALL_COLUMNS:
									System.out.println("未实现");
									break;
								case 2:
									good.setName((String)this.getValueAt(row, col));
									break;
								case 3:
									good.setBrand((String)this.getValueAt(row, col));
									break;
								case 4:
									good.setBrand((String)this.getValueAt(row, col));
									break;
								case 5:
									good.setPrice(new BigDecimal(Float.valueOf((String)this.getValueAt(row, col))));
									break;
								case 6:
									good.setLowerPrice(new BigDecimal(Float.valueOf((String)this.getValueAt(row, col))));
									break;
								case 7:
									good.setDescription((String)this.getValueAt(row, col));
									break;
								case 8:
									good.setPhotos((String)this.getValueAt(row, col));
									break;
								}
								return good;
								//return super.constructObject(firstRow,col);
							}
							@Override
							public void initNullRow(int row) {
								// TODO Auto-generated method stub
								
							}
						},false
						);
				tableView.initDatas(list);
				tableView.setTableController(new TableController<Good>(){
					@Override
					public List<Good> getBackupDatas(SwitchedTableModel<Good> tm) {
						JOptionPane.showMessageDialog(null, "不支持。");
						return null;
					}
					@Override
					public boolean saveChanges(SwitchedTableModel<Good> tm) {
						JOptionPane.showMessageDialog(null, "不支持。");
						return false;
					}
				});
				tabbedPane.addTab(TAB_GOOD_VIEW, tableView);
				tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(tableView), new ButtonTabComponent(tabbedPane));
			}
		});
		mnNewMenu.add(menuItem_2);
		
		JMenu menu_3 = new JMenu("顾客操作");
		mnNewMenu.add(menu_3);
		
		CustomerOperator coAction=new CustomerOperator();
		
		JMenuItem menuItem_4 = new JMenuItem("全览");
		menuItem_4.addActionListener(coAction);
		menuItem_4.setActionCommand(MENU_CUSTOMER_ALL);
		
		
		menu_3.add(menuItem_4);
		
		JMenuItem mntmexcel = new JMenuItem("导出到excel");
		mntmexcel.addActionListener(coAction);
		mntmexcel.setActionCommand(MENU_CUSTOMER_EXPORT);
		menu_3.add(mntmexcel);
		
		JMenuItem menuItem_5 = new JMenuItem("发送消息");
		menuItem_5.addActionListener(coAction);
		menuItem_5.setActionCommand(MENU_CUSTOMER_SEND);
		menu_3.add(menuItem_5);

		JMenu menu = new JMenu("设置");
		menuBar.add(menu);

		JMenu menu_1 = new JMenu("外观");
		menu.add(menu_1);

		SwingAction sa=new SwingAction();
		String windows="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
		JMenuItem lookAndViewWindows = new JMenuItem("windows风格");
		lookAndViewWindows.setActionCommand(windows);
		lookAndViewWindows.addActionListener(sa);
		menu_1.add(lookAndViewWindows);


		Properties prop = new Properties();
		try {
			prop.load(new InputStreamReader(App.class.getResourceAsStream("/conf/ui")));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		for(Object key:prop.keySet()){
			String cmd=(String) prop.get(key);
			JMenuItem mntmNewMenuItem=null;

			mntmNewMenuItem = new JMenuItem((String)key);


			mntmNewMenuItem.setActionCommand(cmd);
			mntmNewMenuItem.addActionListener(sa);
			menu_1.add(mntmNewMenuItem);
		}



		JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem("修改标题栏");
		checkBoxMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(((JCheckBoxMenuItem)e.getSource()).isSelected()){
					JFrame.setDefaultLookAndFeelDecorated(true);
				}else{
					JFrame.setDefaultLookAndFeelDecorated(false);	
				}
				SwingUtilities.updateComponentTreeUI(frame);
			}
		});
		menu.add(checkBoxMenuItem);

		JMenu menu_2 = new JMenu("帮助");
		menuBar.add(menu_2);

		JMenuItem menuItem_3 = new JMenuItem("关于");
		menuItem_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

			}
		});
		menu_2.add(menuItem_3);

	}






	public JTabbedPane getTabbedPane() {
		return tabbedPane;
	}

	public List<Good> getGoods() {
		return goods;
	}

	public void setGoods(List<Good> good) {
		goods = good;
	}
	protected JButton makeNavigationButton(String imageName,
			String actionCommand,
			String toolTipText,
			String altText) {
		//Look for the image.
		String imgLocation = "/images/"
				+ imageName;
		URL imageURL = App.class.getResource(imgLocation);
		String imageUrl="images/"+imageName;
		//Create and initialize the button.
		JButton button = new ImageButton();

		//		button.setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0
		//		button.setIconTextGap(0);//将标签中显示的文本和图标之间的间隔量设置为0
		//		button.setBorderPainted(false);//不打印边框
		//		//button.setBorder(null);//除去边框
		//		button.setText(null);//除去按钮的默认名称
		//		button.setFocusPainted(false);//除去焦点的框
		//		button.setContentAreaFilled(false);//除去默认的背景填充


		button.setActionCommand(actionCommand);
		button.setToolTipText(toolTipText);
		button.addActionListener(actionListener);
		ImageIcon icon=null;
		if (imageURL != null) {
			if(imageURL.getPath().toLowerCase().endsWith("ico")){
//				ICOFile ico;
//				try {
//					ico = new ICOFile(imageUrl);
//					Image image=((Image) ico.getImages().get(0)).getScaledInstance(22, 22, Image.SCALE_SMOOTH);
//					icon=new ImageIcon(image);
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
			}
			else if(imageURL.getPath().toLowerCase().endsWith("png")){
				try {
					Image image=ImageIO.read(imageURL).getScaledInstance(22, 22,  Image.SCALE_SMOOTH);
					icon=new ImageIcon(image);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else {
				icon=new ImageIcon(imageUrl);
			}
			if(icon!=null)
				button.setIcon(icon);
		} else {                                     //no image found
			button.setText(altText);
			System.err.println("Resource not found: "
					+ imgLocation);
		}
		return button;
	}
	@SuppressWarnings("unchecked")
	private void initDatas(){
		Home home=new Home();
		goods=home.list(Home.LIST_GOODS,null);
		home.closeEntityManager();
	}
	private ActionListener actionListener=new ActionListener(){
		@Override
		public void actionPerformed(ActionEvent e) {
			String cmd = e.getActionCommand();

			// Handle each button.
			if (CUSTOMER.equals(cmd)) { //first button clicked

				int index=tabbedPane.indexOfTab(TAB_CUSTOMER1);
				if(index==-1){
					MainUI mainUI=new MainUI();
					tabbedPane.add(TAB_CUSTOMER1,mainUI);
					tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(mainUI), new ButtonTabComponent(tabbedPane));
				}else{
					tabbedPane.setSelectedIndex(index);
				}
			} else if (USER.equals(cmd)) { // second button clicked

			}else if(App.ADD_CUSTOMER.equals(cmd)){
				CustomerAccountUI ca=new CustomerAccountUI();
				tabbedPane.add(App.TAB_ADD_CUSTOMER,ca);
				tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(ca), new ButtonTabComponent(tabbedPane));
				tabbedPane.setSelectedComponent(ca);
			}
		}
	};
	
	public class ImageButton extends JButton {

		private static final long serialVersionUID = 930753529761809104L;
		public ImageButton(){
			initUI();
		}
		public ImageButton(ImageIcon icon){
			setSize(icon.getImage().getWidth(null),
					icon.getImage().getHeight(null));
			setIcon(icon);
		}
		private void  initUI(){
			setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0
			setIconTextGap(0);//将标签中显示的文本和图标之间的间隔量设置为0
			//setBorderPainted(false);//不打印边框
			//setBorder(null);//除去边框
			setText(null);//除去按钮的默认名称
			setFocusPainted(false);//除去焦点的框
			setContentAreaFilled(false);//除去默认的背景填充
			//不对Button进行填充，就是按键是透明的
			setContentAreaFilled(false);
			//按键不能获得焦点
			setFocusable(false);
			//设置按键的边框为雕刻样式
			setBorder(BorderFactory.createEtchedBorder());
			//系统不自动绘制按键边界（这个边界在鼠标放上去之后才绘制）
			setBorderPainted(false);
			this.addMouseListener(mouseListener);
		}
		private final MouseListener mouseListener = new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent event) {
				//鼠标移入按键，绘制按键边界
				Component c = event.getComponent();
				if(c instanceof AbstractButton)
					((AbstractButton)c).setBorderPainted(true);
			}

			@Override
			public void mouseExited(MouseEvent event) {
				//鼠标移出按键，不绘制按键边界
				Component c = event.getComponent();
				if(c instanceof AbstractButton)
					((AbstractButton)c).setBorderPainted(false);
			}

		};

	}

	private class SwingAction implements ActionListener {
		public SwingAction() {
		}
		public void actionPerformed(ActionEvent e) {
			String cmd=e.getActionCommand();
			System.out.println("test");
			if(cmd.startsWith("Substance")){
				cmd="org.pushingpixels.substance.api.skin."+cmd;

				try {
					SubstanceLookAndFeel slf=(SubstanceLookAndFeel)Class.forName(cmd).newInstance();
					System.out.println(slf);
					UIManager.setLookAndFeel(slf);
					SwingUtilities.updateComponentTreeUI(frame);
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				} catch (InstantiationException e2) {
					e2.printStackTrace();
				} catch (IllegalAccessException e3) {
					e3.printStackTrace();
				} catch (UnsupportedLookAndFeelException e4) {
					e4.printStackTrace();
				}
			}
			else{
				try {
					UIManager.setLookAndFeel(cmd);
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				} catch (InstantiationException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				} catch (UnsupportedLookAndFeelException e1) {
					e1.printStackTrace();
				}
				SwingUtilities.updateComponentTreeUI(frame);

			}

		}

	}
	
	class CustomerOperator implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			String cmd=e.getActionCommand();
			if(cmd.equals(MENU_CUSTOMER_SEND)){
				//发送消息
				sendMessage();	
			}
			else if(cmd.equals(MENU_CUSTOMER_EXPORT)){
				//导出信息
				export();
			}
			else if(cmd.equals(MENU_CUSTOMER_ALL)){
				search();
				
			}
		}
		
	}
	
	
	
	protected void search() {
		Home home=new Home();
		try{
			List<CustomerAccount> customers=null;
			customers=home.list(Home.GET_CUSTOMERS,null);
			int result=0;
			if(customers==null||customers.size()==0){
				result=JOptionPane.showConfirmDialog(this.frame, "没有用户的记录", "查询反馈", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE);
			}
			else{
				 tv=new CustomerAccountViewUI(customers,100);
				tabbedPane.add(App.TAB_CUSTOMER2,tv);
				tabbedPane.setSelectedComponent(tv);
				tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(tv), new ButtonTabComponent(tabbedPane));
				JTable jt=tv.getTable();
				jt.addMouseListener(new MouseAdapter(){
					@Override
					public void mouseClicked(MouseEvent e) {
						selectUser();
					}
				});
			}
		}finally{
			home.closeEntityManager();
		}
	}
	public void sendMessage() {
		JOptionPane.showConfirmDialog(this.frame, "暂未实现", "提示", JOptionPane.CLOSED_OPTION, JOptionPane.WARNING_MESSAGE);
		
	}
	public void export() {
		Home home=new Home();
		try{
			List<CustomerAccount> customers=null;
			customers=home.list(Home.GET_CUSTOMERS,null);
			int result=0;
			if(customers==null||customers.size()==0){
				result=JOptionPane.showConfirmDialog(this.frame, "没有用户的记录", "查询反馈", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			}
			else{
				result=JOptionPane.showConfirmDialog(this.frame, "点击确定开始导出客户信息到excel...", "提示", JOptionPane.CLOSED_OPTION, JOptionPane.WARNING_MESSAGE);
				List<Object[]> phonelist = new ArrayList<Object[]>();
				Set<String> phoneSet=new HashSet<String>();
				List<Object[]> emaillist = new ArrayList<Object[]>();
				Set<String> emailSet=new HashSet<String>();
				for(CustomerAccount ca:customers){
					//phone
					if(!phoneSet.contains(ca.getCustomer().getPhone())){
						phoneSet.add(ca.getCustomer().getPhone());
						phonelist.add(new Object[] { ca.getName(), ca.getCustomer().getPhone()});
					}
					if(ca.getTel()!=null&&!phoneSet.contains(ca.getTel())){
						phoneSet.add(ca.getCustomer().getPhone());
						phonelist.add(new Object[] { ca.getName(), ca.getTel()});
					}
					//email
					if(ca.getEmail()!=null&&!emailSet.contains(ca.getEmail())){
						emailSet.add(ca.getEmail());
						emaillist.add(new Object[] { ca.getName(), ca.getEmail()});
					}
				}
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
				String date = sdf.format(new Date());
				String excelName=date+"(电话).xls";
				new File("excel").mkdirs();
				String excelPath =  "excel/"+excelName;
				try {
					ExcelUtil.generateExcel(excelPath, excelName, new String[] {
							"姓名", "联系方式" }, phonelist);
					excelName=date+"(email).xls";
					excelPath = "excel/"+ excelName;
					ExcelUtil.generateExcel(excelPath, excelName, new String[] {
							"姓名", "邮箱"}, emaillist);
					result=JOptionPane.showConfirmDialog(this.frame, "导出完毕，请到软件目录下查看生成文件", "提示", JOptionPane.CLOSED_OPTION, JOptionPane.WARNING_MESSAGE);
					java.awt.Desktop.getDesktop().open(new File("excel"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					result=JOptionPane.showConfirmDialog(this.frame, "导出失败！！！", "提示", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE);		
				}
			}
		}finally{
			home.closeEntityManager();
		}
	}
	private void selectUser(){
		if(tv==null){
			JOptionPane.showConfirmDialog(this.frame, "错误的操作", "error", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			return;
		}
		if(tv.getTable().getSelectedColumn()==9){
			@SuppressWarnings("unchecked")
			ClassModel<CustomerAccount> cm=(ClassModel<CustomerAccount>) tv.getTable().getValueAt(tv.getTable().getSelectedRow(),0);
			CustomerAccount ca=cm.getObject();
			CustomerRecordViewUI crui=new CustomerRecordViewUI(ca);
			tabbedPane.setSelectedComponent(
					tabbedPane.add(ca.getName()+App.TAB_CUSTOMERRECORDS,crui)
					);
			tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(crui), new ButtonTabComponent(tabbedPane));
		}
	}
}


